package org.seamon.management.controller;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.seamon.management.pojo.dto.DeptInsertDto;
import org.seamon.management.pojo.dto.DeptUpdateDto;
import org.seamon.management.service.DeptService;
import org.seamon.management.util.Result;
import org.seamon.management.util.aspect.Limit;
import org.seamon.management.util.aspect.Log;
import org.seamon.management.util.enums.BusinessTypeEnum;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/dept")
@Slf4j
@Validated
public class DeptController {
    @Resource
    private DeptService deptService;

    @PreAuthorize("hasAuthority('dept:list')")
    @Log(title = "获取机构树列表", businessType = BusinessTypeEnum.LIST)
    @GetMapping("/list")
    public Result<?> listTree() {
        log.info("获取机构树列表");
        return Result.success(deptService.listTree());
    }

    @Limit(key = "dept_save", permitsPerSecond = 1, timeout = 5, timeunit = TimeUnit.SECONDS)
    @PreAuthorize("hasAuthority('dept:add')")
    @Log(title = "新增机构", businessType = BusinessTypeEnum.ADD)
    @PostMapping()
    public Result<?> save(@RequestBody @Valid DeptInsertDto deptDto) {
        log.info("保存机构: {}", deptDto);
        deptService.save(deptDto);
        return Result.success();
    }

    @Limit(key = "dept_update", permitsPerSecond = 10, timeout = 1, timeunit = TimeUnit.SECONDS)
    @PreAuthorize("hasAuthority('dept:edit')")
    @Log(title = "修改机构", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping()
    public Result<?> update(@RequestBody @Valid DeptUpdateDto deptDto) {
        log.info("更新机构, id: {}, 更新内容：{}", deptDto.getId(), deptDto);
        deptService.updateById(deptDto);
        return Result.success();
    }

    @Limit(key = "dept_delete", permitsPerSecond = 10, timeout = 1, timeunit = TimeUnit.SECONDS)
    @PreAuthorize("hasAuthority('dept:delete')")
    @Log(title = "删除机构", businessType = BusinessTypeEnum.DELETE)
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        log.info("删除机构, id: {}", id);
        deptService.removeById(id);
        return Result.success();
    }
}
